package com.cloudy.impl;

import com.cloudy.exception.AWSAccessException;
import com.cloudy.exception.S3AccessException;
import com.cloudy.s3.response.error.ErrorResponseItemType;
import com.cloudy.utility.CloudyUtility;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

class S3ErrorResponseHandler extends ErrorResponseHandler {
    private Logger logger = Logger.getLogger(this.getClass().getName());
        private JAXBContext ctx;

        public S3ErrorResponseHandler() {
            try {
                ctx = JAXBContext.newInstance("com.cloudy.s3.response:com.cloudy.s3.response.error");
            } catch (JAXBException e) {
                throw new RuntimeException(e);
            }
        }


    public void handleException(InputStream errorStream) throws AWSAccessException {
        Object result =
                unmarshalTheResponse(errorStream);
        if (result instanceof ErrorResponseItemType) {
            ErrorResponseItemType error = (ErrorResponseItemType) result;
            throw new S3AccessException(error);
        } else {
            logger.log(Level.WARNING, result.toString());
        }
    }
    @Override
    public Object unmarshalTheResponse(InputStream stream) throws S3AccessException {
        Object t = null;
        try {
            t = CloudyUtility.unmarshalTheResponse(ctx, stream);
        } catch (Exception e) {
            throw new S3AccessException(e);
        }
        return t;
    }
}